package com.hmall.cart.listener;

import com.hmall.cart.service.ICartService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class CartClearListener {
    
    private final ICartService cartService;
    
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = "trade.topic", type = "topic"),
            value = @Queue(name = "cart.clear.queue"),
            key = "order.create"
    ))
    public void listenCartClear(Map<String, Object> msg) {
        try {
            Long userId = (Long) msg.get("userId");
            Collection<Long> itemIds = (Collection<Long>) msg.get("itemIds");
            
            // 清理购物车中的指定商品
            cartService.removeByItemIds(itemIds);
        } catch (Exception e) {
            // 记录日志，处理异常，避免影响消息队列的正常消费
            System.err.println("处理购物车清理消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}